package com.software.levelupandroid.taskIssue.view.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.loper7.date_time_picker.DateTimeConfig;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;
import com.software.levelupandroid.R;
import com.software.levelupandroid.taskIssue.view.activity.TaskIssueActivity;
import com.software.levelupandroid.taskIssue.view.adapter.ReminderTimeAdapter;
import com.software.levelupandroid.utils.DateUtil;
import com.software.levelupandroid.views.NumberCountView;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.HashMap;

/**
 * @Description TODO
 * @Author LiangYaJie
 * @CreateTime 2024年05月07日 09:35:11
 */
public class TimingTaskFragment extends Fragment {
    private TextView tvTimingTaskStartTime, tvTimingTaskEndTime;
    private TextView tvTimingTaskStartDate, tvTimingTaskEndDate;
    private RelativeLayout rlTimingTaskReminder;
    private TextView tvTimingTaskReminder;
    private RecyclerView recyclerView;
    private ReminderTimeAdapter reminderTimeAdapter;
    private HashMap<ToggleButton, TextView> toggleButtonTextViewMap = new HashMap<>();
    private Long startTime;
    private LocalDateTime startLocalDateTime;
    private LocalDateTime dateTimeRemind1;
    private String oneReminderContent; //临时存储选择的提醒时间内容变量
    private TaskIssueActivity taskIssueActivity;

    @Override
    @Nullable
    @SuppressLint("MissingInflatedId")
    @RequiresApi(api = Build.VERSION_CODES.O)
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_timing_task, container, false);

        tvTimingTaskStartTime = view.findViewById(R.id.tv_timing_task_startTime);
        tvTimingTaskEndTime = view.findViewById(R.id.tv_timing_task_endTime);
        tvTimingTaskStartDate = view.findViewById(R.id.tv_timing_task_startDate);
        tvTimingTaskEndDate = view.findViewById(R.id.tv_timing_task_endDate);
        rlTimingTaskReminder = view.findViewById(R.id.rl_timing_task_reminder);
        tvTimingTaskReminder = view.findViewById(R.id.tv_timing_task_reminder);
        recyclerView = view.findViewById(R.id.rv_timing_task_reminder);

        if (taskIssueActivity.getTask().getStartTime() != null){
            String start = taskIssueActivity.getTask().getStartTime();
            tvTimingTaskStartDate.setText(start.substring(0,10));
            tvTimingTaskStartTime.setText(start.substring(11));
            startTime = DateUtil.convertStringToLong(start, "yyyy年MM月dd日 HH:mm");
            startLocalDateTime = DateUtil.convertStringToLocalDateTime(start, "yyyy年MM月dd日 HH:mm");
        }

        if (taskIssueActivity.getTask().getEndTime() != null){
            String end = taskIssueActivity.getTask().getEndTime();
            tvTimingTaskEndDate.setText(end.substring(0,10));
            tvTimingTaskEndTime.setText(end.substring(11));
        }

        if(taskIssueActivity.getTask().getRemind3() != null){
            tvTimingTaskReminder.setText("提醒3次");
            Drawable drawable2 = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_down_24);
            tvTimingTaskReminder.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable2,null);
            reminderTimeAdapter = new ReminderTimeAdapter(getContext(), 3, taskIssueActivity.getTask());
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            recyclerView.setAdapter(reminderTimeAdapter);
        }else {
            if (taskIssueActivity.getTask().getRemind2() != null){
                tvTimingTaskReminder.setText("提醒2次");
                Drawable drawable2 = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_down_24);
                tvTimingTaskReminder.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable2,null);
                reminderTimeAdapter = new ReminderTimeAdapter(getContext(), 2, taskIssueActivity.getTask());
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                recyclerView.setAdapter(reminderTimeAdapter);
            }else if (taskIssueActivity.getTask().getRemind1() != null){
                Drawable drawable0 = ContextCompat.getDrawable(getContext(), R.drawable.baseline_chevron_right_24);
                tvTimingTaskReminder.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable0,null);
                recyclerView.setAdapter(null);

                LocalDateTime remind1 = DateUtil.convertStringToLocalDateTime(taskIssueActivity.getTask().getRemind1(), "yyyy年MM月dd日 HH:mm");
                if (remind1.compareTo(startLocalDateTime) == 0){
                    tvTimingTaskReminder.setText("准时提醒");
                }else {
                    long durationMinutes = DateUtil.getTimeDuration(startLocalDateTime, remind1);
                    System.out.println("durationMinutes: " + durationMinutes);
                    Log.e("durationMinutes", durationMinutes + "");

                    if (durationMinutes % 60*24 == 0){
                        tvTimingTaskReminder.setText("提前" + durationMinutes/(60*24) + "天");
                    }else {
                        if (durationMinutes % 60 == 0){
                            tvTimingTaskReminder.setText("提前" + durationMinutes/60 + "小时");
                        }else {
                            tvTimingTaskReminder.setText("提前" + durationMinutes + "分钟");
                        }
                    }
                }


            }
        }

        //设置开始时间按键的点击监听
        tvTimingTaskStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCardDatePickerDialogStart();
            }
        });

        //设置结束时间按键的点击监听
        tvTimingTaskEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCardDatePickerDialogEnd();
            }
        });

        //设置对提醒时间按键的点击监听
        rlTimingTaskReminder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (startLocalDateTime == null)
                    Toast.makeText(taskIssueActivity, "请先设置开始时间", Toast.LENGTH_SHORT).show();
                else
                    showReminderDialog();
            }
        });

        return view;
    }

    /**
     * fragment的onAttach()生命周期，在此生命周期中实现Fragment持有对宿主Activity的引用
     * @param context
     */
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof TaskIssueActivity){
            taskIssueActivity = (TaskIssueActivity) context;
        }
    }

    //提醒次数选项的弹窗
    private void showReminderDialog() {
        String[] items = {"提醒1次", "提醒2次", "提醒3次"};
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());

        dialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                switch (i){
                    case 0:
//                        tvTimingTaskReminder.setText("准时提醒");

                        showBottomOneReminderDialog();
                        break;
                    case 1:
                        tvTimingTaskReminder.setText("提醒"+(i+1)+"次");
                        Drawable drawable1 = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_down_24);
                        tvTimingTaskReminder.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable1,null);
                        reminderTimeAdapter = new ReminderTimeAdapter(getContext(), i+1, taskIssueActivity.getTask());
                        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                        recyclerView.setAdapter(reminderTimeAdapter);
                        break;
                    case 2:
                        tvTimingTaskReminder.setText("提醒"+(i+1)+"次");
                        Drawable drawable2 = ContextCompat.getDrawable(getContext(), R.drawable.baseline_keyboard_arrow_down_24);
                        tvTimingTaskReminder.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable2,null);
                        reminderTimeAdapter = new ReminderTimeAdapter(getContext(), i+1, taskIssueActivity.getTask());
                        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                        recyclerView.setAdapter(reminderTimeAdapter);
                        break;
                }
            }
        });
        dialog.show();
    }

    //展开“一次提醒”的底部弹窗
    @SuppressLint("MissingInflatedId")
    private void showBottomOneReminderDialog() {
        //更新task中的内容
        taskIssueActivity.getTask().setRemind2(null);
        taskIssueActivity.getTask().setRemind3(null);

        //定义底部弹窗，并展示
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getContext(), R.style.BottomSheetDialog);
        View bottomView = LayoutInflater.from(getContext()).inflate(R.layout.bottom_sheet_dialog_task_reminder, null);
        bottomSheetDialog.setContentView(bottomView);
        bottomSheetDialog.show();

        //控件绑定
        TextView tvTaskRCancel = bottomView.findViewById(R.id.tv_bsd_taskR_cancel);
        TextView tvTaskREnsure = bottomView.findViewById(R.id.tv_bsd_taskR_ensure);

        toggleButtonTextViewMap.put(bottomView.findViewById(R.id.tb_bsd_reminder_01), bottomView.findViewById(R.id.tv_bsd_reminder_01));
        toggleButtonTextViewMap.put(bottomView.findViewById(R.id.tb_bsd_reminder_02), bottomView.findViewById(R.id.tv_bsd_reminder_02));
        toggleButtonTextViewMap.put(bottomView.findViewById(R.id.tb_bsd_reminder_03), bottomView.findViewById(R.id.tv_bsd_reminder_03));
        toggleButtonTextViewMap.put(bottomView.findViewById(R.id.tb_bsd_reminder_04), bottomView.findViewById(R.id.tv_bsd_reminder_04));
        toggleButtonTextViewMap.put(bottomView.findViewById(R.id.tb_bsd_reminder_05), bottomView.findViewById(R.id.tv_bsd_reminder_05));
        toggleButtonTextViewMap.put(bottomView.findViewById(R.id.tb_bsd_reminder_06), null);
        toggleButtonTextViewMap.put(bottomView.findViewById(R.id.tb_bsd_reminder_07), null);

        ToggleButton tbBsdReminder06= bottomView.findViewById(R.id.tb_bsd_reminder_06);
        ToggleButton tbBsdReminder07= bottomView.findViewById(R.id.tb_bsd_reminder_07);
        NumberCountView numberCountView06 = bottomView.findViewById(R.id.ncv_bsd_reminder_06);
        NumberCountView numberCountView07 = bottomView.findViewById(R.id.ncv_bsd_reminder_07);

        //设置简单选项的点击事件
        for (ToggleButton toggleButton : toggleButtonTextViewMap.keySet()){
            toggleButton.setOnClickListener(new View.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onClick(View view) {
                    TextView tvBsdReminder = toggleButtonTextViewMap.get(toggleButton);
                    oneReminderContent = tvBsdReminder.getText().toString();
                    switch (oneReminderContent){
                        case "准时提醒":
                            dateTimeRemind1 = startLocalDateTime;
//                            String remind1 = DateUtil.convertLocalDateTimeToString(startLocalDateTime, "yyyy年MM月dd日 HH:mm");
//                            taskIssueActivity.getTask().setRemind1(remind1);
                            break;
                        case "提前10分钟":
                            dateTimeRemind1 = startLocalDateTime.minusMinutes(10);
//                            String remindMinus10 = DateUtil.convertLocalDateTimeToString(dateTimeMinus10, "yyyy年MM月dd日 HH:mm");
//                            taskIssueActivity.getTask().setRemind1(remindMinus10);
                            break;
                        case "提前20分钟":
                            dateTimeRemind1 = startLocalDateTime.minusMinutes(20);
//                            String remindMinus20 = DateUtil.convertLocalDateTimeToString(dateTimeMinus20, "yyyy年MM月dd日 HH:mm");
////                            taskIssueActivity.getTask().setRemind1(remindMinus20);
                            break;
                        case "提前30分钟":
                            dateTimeRemind1 = startLocalDateTime.minusMinutes(30);
//                            String remindMinus30 = DateUtil.convertLocalDateTimeToString(dateTimeMinus30, "yyyy年MM月dd日 HH:mm");
////                            taskIssueActivity.getTask().setRemind1(remindMinus30);
                            break;
                        case "提前1小时":
                            dateTimeRemind1 = startLocalDateTime.minusHours(1);
//                            String remindMinusHours1 = DateUtil.convertLocalDateTimeToString(dateTimeMinusHours1, "yyyy年MM月dd日 HH:mm");
////                            taskIssueActivity.getTask().setRemind1(remindMinusHours1);
                            break;
                        default:
                            break;
                    }
                    //将其他按钮状态设置为未选状态
                    for (ToggleButton button : toggleButtonTextViewMap.keySet()){
                        if (button != toggleButton){
                            button.setChecked(false);
                        }
                    }
                }
            });
        }

        //设置底部弹窗的“取消”、“确定”以及复杂选项的点击事件
        View.OnClickListener clickListener = new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.tb_bsd_reminder_06:
                        int minute = numberCountView06.getCurrentValue();
                        oneReminderContent = "提前" + minute + "分钟";
                        //将提前时间后的提醒时间存入task的remind1中
                        dateTimeRemind1 = startLocalDateTime.minusMinutes(minute);
//                        if (DateUtil.convertLocalDateTimeToLong(dateTimeMinusMinute) < DateUtil.getNowTimeLong()){
//                            Toast.makeText(taskIssueActivity, "选择的提醒时间已过", Toast.LENGTH_SHORT).show();
//                        }else {
//                            String remindMinusMinute = DateUtil.convertLocalDateTimeToString(dateTimeMinusMinute, "yyyy-MM-dd HH:mm");
//                            taskIssueActivity.getTask().setRemind1(remindMinusMinute);
//                        }
                        for (ToggleButton button : toggleButtonTextViewMap.keySet()){
                            if (button != tbBsdReminder06){
                                button.setChecked(false);
                            }
                        }
                        break;
                    case R.id.tb_bsd_reminder_07:
                        int day = numberCountView07.getCurrentValue();
                        oneReminderContent = "提前" + day + "天";
                        //将提前时间后的提醒时间存入task的remind1中
                        dateTimeRemind1 = startLocalDateTime.minusDays(day);
//                        String remindMinusDays = DateUtil.convertLocalDateTimeToString(dateTimeMinusDays, "yyyy-MM-dd HH:mm");
//                        taskIssueActivity.getTask().setRemind1(remindMinusDays);
                        for (ToggleButton button : toggleButtonTextViewMap.keySet()){
                            if (button != tbBsdReminder07){
                                button.setChecked(false);
                            }
                        }
                        break;
                    case R.id.tv_bsd_taskR_ensure:
                        if (oneReminderContent.equals("")){
                            tvTimingTaskReminder.setText("准时提醒");
                            String remind1 = DateUtil.convertLocalDateTimeToString(startLocalDateTime, "yyyy年MM月dd日 HH:mm");
                            taskIssueActivity.getTask().setRemind1(remind1);
                            Drawable drawable0 = ContextCompat.getDrawable(getContext(), R.drawable.baseline_chevron_right_24);
                            tvTimingTaskReminder.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable0,null);
                            recyclerView.setAdapter(null);
                            bottomSheetDialog.dismiss();
                        }else {
                            if (DateUtil.convertLocalDateTimeToLong(dateTimeRemind1) < DateUtil.getNowTimeLong()){
                                Toast.makeText(taskIssueActivity, "选择的提醒时间已过", Toast.LENGTH_SHORT).show();
                            }else {
                                String remind1 = DateUtil.convertLocalDateTimeToString(dateTimeRemind1, "yyyy年MM月dd日 HH:mm");
                                taskIssueActivity.getTask().setRemind1(remind1);
                                tvTimingTaskReminder.setText(oneReminderContent);
                                Drawable drawable0 = ContextCompat.getDrawable(getContext(), R.drawable.baseline_chevron_right_24);
                                tvTimingTaskReminder.setCompoundDrawablesWithIntrinsicBounds(null,null,drawable0,null);
                                recyclerView.setAdapter(null);
                                bottomSheetDialog.dismiss();
                            }
                        }
                        break;
                    case R.id.tv_bsd_taskR_cancel:
                        bottomSheetDialog.dismiss();
                        break;
                }
            }
        };

        tvTaskRCancel.setOnClickListener(clickListener);
        tvTaskREnsure.setOnClickListener(clickListener);
        tbBsdReminder06.setOnClickListener(clickListener);
        tbBsdReminder07.setOnClickListener(clickListener);

    }

    //选择结束时间
    private void showCardDatePickerDialogEnd() {
        Calendar calendar = Calendar.getInstance();

        CardDatePickerDialog cardDatePickerDialog = new CardDatePickerDialog.Builder(getContext())
                .setTitle("结束时间选择")
                .showBackNow(false)
                .setOnChoose("确定", aLong -> {
                    if (startTime < aLong){
                        String endDate = DateUtil.convertDateSecondToString(aLong, "yyyy年MM月dd日");
                        String endTime = DateUtil.convertDateSecondToString(aLong, "HH:mm");
                        taskIssueActivity.getTask().setEndTime(endDate + " " + endTime); //将结束时间放入task实例
                        tvTimingTaskEndDate.setText(endDate);
                        tvTimingTaskEndTime.setText(endTime);
                    }else {
                        Toast.makeText(getActivity(), "结束时间早于开始时间", Toast.LENGTH_SHORT).show();
                    }

                    return null;
                })
                .setBackGroundModel(CardDatePickerDialog.CARD)
                .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY, DateTimeConfig.HOUR, DateTimeConfig.MIN)
                .setDefaultTime(calendar.getTimeInMillis())
                .setLabelText("年", "月", "日", "时", "分", "秒")
                .build();
        cardDatePickerDialog.show();
    }

    //选择开始时间
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void showCardDatePickerDialogStart() {

        Calendar calendar = Calendar.getInstance();

        CardDatePickerDialog cardDatePickerDialog = new CardDatePickerDialog.Builder(getContext())
                .setTitle("开始时间选择")
                .showBackNow(false)
                .setOnChoose("确定", aLong -> {
                    if (aLong < DateUtil.getNowTimeLong()) {
                        Toast.makeText(taskIssueActivity, "选择的开始时间已过", Toast.LENGTH_SHORT).show();
                    }else {
                        startTime = aLong;
                        startLocalDateTime = DateUtil.convertLongToLocalDateTime(aLong);
                        String startDate = DateUtil.convertDateSecondToString(aLong, "yyyy年MM月dd日");
                        String startTime = DateUtil.convertDateSecondToString(aLong, "HH:mm");
                        taskIssueActivity.getTask().setStartTime(startDate + " " + startTime); //将开始时间放入task实例
                        taskIssueActivity.getTask().setRemind1(startDate + " " + startTime); //默认在选择开始时间之后，提醒时间设置为按时开始
                        tvTimingTaskStartDate.setText(startDate);
                        tvTimingTaskStartTime.setText(startTime);
                    }

                    return null;
                })
                .setBackGroundModel(CardDatePickerDialog.CARD)
                .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY, DateTimeConfig.HOUR, DateTimeConfig.MIN)
                .setDefaultTime(calendar.getTimeInMillis())
                .setLabelText("年", "月", "日", "时", "分", "秒")
                .build();
        cardDatePickerDialog.show();
    }
}
